const puppeteer = require('puppeteer');
let index = 0;
let targetUrl = 'https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%D0%A1%BD%E3%BD%E3&fr=ala&ala=1&alatpl=adress&pos=0&hs=2&xthttps=111111';

function sleep(delay) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            try {
                resolve(1)
            } catch (e) {
                reject(0)
            }
        }, delay)
    })
}

function downLoadImg(imgUrl) {
    let fs = require('fs');
    let http = require('https');
    http.get(imgUrl, function(res){
        let imgData = "";
        let contentLength = parseInt(res.headers['content-length']);
        res.setEncoding("binary");
        res.on("data", function(chunk){
            imgData += chunk;
            let process = ((imgData.length)/contentLength) * 100;
            let percent = parseInt(((process).toFixed(0)));
        });

        res.on("end", function(){
            let date = new Date();
            let nowDate = date.getTime();
            let imgName = nowDate + '.jpg';
            fs.writeFile(`./images/${imgName}`, imgData, "binary", function(err){
                if(err){
                    console.log("down fail");
                }else{
                    index++;
                    console.log('第'+index+'张下载完成');
                }


            });
        });
    });

}




(async () => {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();

    // document.body.clientHeight           页面元素总共的高度
    // let elements = document.querySelectorAll('.imgitem .imgbox');
    // for(let i of elements){
    //     let url = i.querySelector('a').href;
    //     let imgPath = i.querySelector('img').src;
    //     data.push({url,imgPath});
    // }
    await page.goto(targetUrl);

    let scrollEnable = true;
    let scrollStep = 100; //每次滚动的步长
    while (scrollEnable) {
        scrollEnable = await page.evaluate((scrollStep) => {
            let scrollTop = document.scrollingElement.scrollTop;
            document.scrollingElement.scrollTop = scrollTop + scrollStep;
            return document.body.clientHeight < 5000 ? true : false
        }, scrollStep);
        await sleep(100);
    }



    const targetLink = await page.evaluate(()=>{
        let data = [] ;
        let elements = document.querySelectorAll('.imgitem .imgbox');
        for(let i of elements){
            let url = i.querySelector('a').href;
            let imgPath = i.querySelector('img').src;
            data.push({url,imgPath});
        }
        return data
    });



    for(let i of targetLink){
        // console.log(i.imgPath);
        downLoadImg(i.imgPath)
    }



    browser.close();
})();